<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;
use app\common\model\Classes as ClassesModel;
use app\common\model\StudentClassesRelation;
use app\common\model\TeacherClassesRelation;
use app\common\model\User;

/**
 * 班级接口
 */
class Classes extends Api
{
    /**
     * 班级列表
     * @var array
     */
    protected $noNeedLogin = ['scanJoinClasses'];
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $this->studentClassesRelation = new StudentClassesRelation();
        $this->teacherClassesRelation = new TeacherClassesRelation();
        $this->user = new User();
        $this->model = new ClassesModel();
    }

    /**
     * 扫码加入班级
     *
     * @ApiTitle    (扫码加入班级)
     * @ApiSummary  (扫码加入班级)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/classes/scanJoinClasses)
     * @ApiParams   (name="class_id", type="integer", required=true, description="班级ID")
     * @ApiParams   (name="user_id", type="integer", required=true, description="用户ID")
     * @ApiParams   (name="type", type="integer", required=true, description="用户类型，1：学生，2：教师")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
       'code':'200',
       'msg':'加入成功'
       })
     */
    public function scanJoinClasses()
    {
        $data = input('get.');
        $userId = $data['user_id'];
        $classesId = $data['classes_id'];
        $type = $data['type'];
        if(!$userId || !Validate::is($userId, 'number') || !$classesId || !Validate::is($classesId, 'number') ||  !$type || !Validate::is($type, 'number')){
            $this->error('参数错误');
        }
        
        $dis = [
            'id' => $classesId
        ];
        $classes = $this->model->dataInfo($dis);
        if (empty($classes)) {
            $this->error('班级不存在');
        }
        switch ($type) {
            case 1:
                $dis = [
                    'student_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $res = $this->studentClassesRelation->dataInfo($dis);
                if (!empty($res)) {
                    $this->success('已加入班级');
                }
                $dis = [
                    'student_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $this->studentClassesRelation->dataAdd($dis);
                break;
            default:
                $dis = [
                    'teacher_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $res = $this->teacherClassesRelation->dataInfo($dis);
                if (!empty($res)) {
                    $this->success('已加入班级');
                }
                $dis = [
                    'teacher_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $this->teacherClassesRelation->dataAdd($dis);
                break;
        }
        
        $this->success('加入成功');
    }

    /**
     * 加入班级
     * @ApiTitle    (加入班级)
     * @ApiMethod  (GET)
     * @ApiParams (name="user_id", type="int", required=true, description="用户ID")
     * @ApiParams (name="classes_id", type="int", required=true, description="班级ID")
     * @ApiParams (name="type", type="int", required=true, description="用户类型，1：学生，2：教师")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="新增成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'加入成功'
      })
     *
     */
    public function joinClasses()
    {
        $data = input('get.');
        $userId = $data['user_id'];
        $classesId = $data['classes_id'];
        $type = $data['type'];
        if(!$userId || !Validate::is($userId, 'number') || !$classesId || !Validate::is($classesId, 'number') ||  !$type || !Validate::is($type, 'number')){
            $this->error('参数错误');
        }
        
        $dis = [
            'id' => $classesId
        ];
        $classes = $this->model->dataInfo($dis);
        if (empty($classes)) {
            $this->error('班级不存在');
        }
        switch ($type) {
            case 1:
                $dis = [
                    'student_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $res = $this->studentClassesRelation->dataInfo($dis);
                if (!empty($res)) {
                    $this->success('已加入班级');
                }
                $dis = [
                    'student_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $this->studentClassesRelation->dataAdd($dis);
                break;
            default:
                $dis = [
                    'teacher_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $res = $this->teacherClassesRelation->dataInfo($dis);
                if (!empty($res)) {
                    $this->success('已加入班级');
                }
                $dis = [
                    'teacher_id' => $userId,
                    'classes_id' => $classesId,
                ];
                $this->teacherClassesRelation->dataAdd($dis);
                break;
        }
        
        $this->success('加入成功');
    }



    /**
     * 查询班级列表
     * @ApiTitle    (查询班级列表)
     * @ApiParams (name="grade_id", type="int", required=true, description="查询年段ID")
     * @ApiMethod  (GET)
      * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'查询成功',
        'time': "",
        'data': $row
      })
     */
    public function classIndex()
    {
        $data = input('get.');
        $gradeId = $data['grade_id'];
        if (!$gradeId || !Validate::is($gradeId, 'number')) {
            $this->error('年段ID不正确');
        }
        $dis = [
            'grade_id' => $gradeId,
        ];
        $res = $this->model->dataList($dis);
        if (!$res) {
            $this->success('未查询到数据', []);
        }
        $this->success('查询成功', $res);
    }

    /**
     * 新增班级
     * @ApiTitle    (新增班级)
     * @ApiMethod  (POST)
     * @ApiParams (name="user_id", type="number", required=true, description="用户ID")
     * @ApiParams (name="name", type="string", required=true, description="班级名称")
     * @ApiParams (name="avatar", type="string", required=true, description="图片地址")
     * @ApiParams (name="school_id", type="number", required=true, description="学校ID")
     * @ApiParams (name="grade_id", type="number", required=true, description="年级ID")
     * @ApiReturnParams   (name="code", type="number", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="新增成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'新增成功'
      })
     * 
     */
    public function classAdd()
    {

        $data = input('post.');
        $userId = $data['user_id'];
        $avatar = $data['avatar'];
        $name = $data['name'];
        $gradeId = $data['grade_id'];
        $schoolId = $data['school_id'];
        if(!$userId || !Validate::is($userId, 'number') || !$gradeId || !Validate::is($gradeId, 'number') || !$schoolId || !Validate::is($schoolId, 'number') || !$name || !$avatar){
            $this->error('参数错误');
        }
        $dis = [
            'grade_id' => $gradeId,
            'school_id' => $schoolId,
            'name' => $name,
        ];
        
        $row = $this->model->dataInfo($dis);
        if ($row) {
            $this->error('班级已存在');
        }

        $this->model->dataAdd($data);
        $classID = $this->model->getLastInsID();
        // $domainName = $_SERVER['HTTP_HOST'];
        // $param = [
        //     'text' => 'http://' . $domainName . '/api/classes/scanJoinClasses?class_id=' . $classID,
        // ];
        $param = [
            'text' => $classID,
        ];

        $qrCode = \addons\qrcode\library\Service::qrcode($param);
        
        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath . 'class_' . $classID.'.png';
            $qrCode->saveToFile($filePath);
        }

        $data['qrcode_path'] = '/uploads/qrcode/class_' . $classID . '.png'; 
        $res = $this->model->dataUpdate(['id' => $classID],$data);
        if (!$res) {
            $this->error('新增失败');
        }
        $dis = [
            'teacher_id' => $userId,
            'classes_id' => $classID,
        ];
        $this->teacherClassesRelation->dataAdd($dis);
        $this->success('新增成功');
    }

    /**
     * 用户查询创建班级列表
     * @ApiTitle    (查询班级列表)
     * @ApiParams (name="user_id", type="int", required=true, description="查询用户ID")
     * @ApiMethod  (GET)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'查询成功',
        'time': "",
        'data': $row
      })
     */
    public function teacherClassIndex()
    {
        $data = input('get.');
        $user_id = $data['user_id'];
        if( !$user_id || !Validate::is($user_id, 'number')){
            $this->error('参数类型不正确');
        }

        $dis = [
            'id' => $user_id,
        ];
        $userInfo = $this->user->dataInfo($dis, ['id', 'username', 'avatar', 'nickname']);
        if (!$userInfo) {
            $this->error('用户信息不存在');
        }

        $dis = [
            'teacher_id' => $user_id,
        ];
        $teacher_classes = $this->teacherClassesRelation->dataList($dis);
        if (!$teacher_classes) {
            $this->success('该用户没有加入任何班级', []);
        }
        $classIds = array_column($teacher_classes, 'classes_id');
        $rows = $this->model->dataList(null, 'id', $classIds);
        $classIds = array_column($rows, 'id');
        $studentCounts = $this->studentClassesRelation->dataCount(
            ['classes_id' => ['in', $classIds]],
            'classes_id'
        );
        foreach ($rows as &$row) {
            $row['teacher'] = $userInfo; // 添加教师信息
            $row['student_count'] = $studentCounts[$row['id']] ?? 0; // 添加学生人数统计
        }
        $this->success('查询成功', $rows);
    }

    /**
     * 班级详情
     * @ApiTitle    (班级详情)
     * @ApiParams (name="class_id", type="int", required=true, description="班级ID")
     * @ApiMethod  (GET)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'查询成功',
        'time': "",
        'data': $row
      })
     */
    public function classDetail()
    {
        $data = input('get.');
        $classId = $data['class_id'];
        if(!$classId || !Validate::is($classId, 'number')){
            $this->error('班级ID不正确');
        }

        $dis = [
            'id' => $classId,
        ];

        $row = $this->model->dataInfo($dis);
        if(empty($row)){
            $this->success('查询的班级不存在',[]);
        }
        $dis = [
            'classes_id' => $classId,
        ];
        $row['teacher_count'] = $this->teacherClassesRelation->dataCount($dis,null);
        $row['student_count'] = $this->studentClassesRelation->dataCount($dis,null);

        $teacherIds = $this->teacherClassesRelation->dataMemberId($dis, 'teacher_id') ?: [];
        if($teacherIds){
            $row['teacher'] = $this->user->dataList(['id' => ['in', $teacherIds]], 'id,username,avatar,nickname');
        }else{
            $row['teacher'] = [];
        }

        $studentIds = $this->studentClassesRelation->dataMemberId($dis, 'student_id') ?: [];
        if($studentIds){
            $row['student'] = $this->user->dataList(['id' => ['in', $studentIds]], 'id,username,avatar,nickname');
        }else{
            $row['student'] = [];
        }
        
        $this->success('查询成功', $row);
    }

}
